<template>
  <div class="px-10px">
    <!-- 按仓库循环 -->
    <div v-for="(wid, warehouseIndex) in widList" :key="wid">
      <div class="font-bold text-lg mb-4"> {{ getWarehouseName(wid) }}</div>

      <!-- 当前仓库的梯度项 -->
      <div
        v-for="(current, currentIndex) in getGradientsByWid(wid)"
        :key="`${wid}-${current.level}`"
      >
        <div class="flex justify-end flex-items-center m-b-20px">
          <div v-if="current.level === 1">
            <!-- 新增按钮：当梯度数 < 币种总数时显示 -->
            <el-button
              v-if="getGradientsByWid(wid).length < currencyLists[warehouseIndex]?.length"
              @click="handleItemAdd(warehouseIndex)"
            >
              新增
            </el-button>
            <!-- 删除按钮：只在新增梯度项后显示 -->
            <el-button
              v-if="getGradientsByWid(wid).length > 1"
              type="danger"
              @click="handleLastItemDelete(wid)"
            >
              删除
            </el-button>
          </div>
        </div>

        <el-card shadow="never" class="mb-6">
          <el-form
            :model="current"
            :rules="rules"
            :ref="(el: any) => setFormRef(warehouseIndex, currentIndex, el)"
            label-width="120px"
          >
            <el-form-item label="币种" prop="currency_id">
              <el-select
                v-model="current.currency_id"
                placeholder="请选择币种"
                :clearable="false"
                style="width: 100%"
                @change="(e) => handleChangeCurrency(currentIndex, e)"
              >
                <el-option
                  v-for="item in currencyLists[warehouseIndex]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="头程物流费" prop="first_leg_logistics_fee">
              <el-input
                v-model="current.first_leg_logistics_fee"
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="产品价格" prop="price">
              <el-input
                v-model="current.price"
                placeholder="请输入"
                @input="handlePriceInput(current)"
                style="width: 100%"
              />
            </el-form-item>

            <div v-if="current.discount && current.discount.length">
              <div
                v-for="(currentGradient, currentGradientIndex) in current.discount"
                :key="currentGradient.level"
              >
                <el-row :gutter="24" align="middle">
                  <el-col :span="7">
                    <el-form-item
                      :label="`数量 ${currentGradient.level}`"
                      :prop="'discount.' + currentGradientIndex + '.num'"
                      :rules="ruleFn('num', current.discount, currentGradientIndex)"
                    >
                      <el-input-number
                        v-model="currentGradient.num"
                        :min="1"
                        :precision="0"
                        placeholder="请输入"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="7">
                    <el-form-item
                      :label="`折扣价格 ${currentGradient.level}`"
                      :prop="'discount.' + currentGradientIndex + '.sales_price'"
                      :rules="ruleFn('sales_price', current.discount, currentGradientIndex)"
                    >
                      <el-input-number
                        v-model="currentGradient.sales_price"
                        :precision="2"
                        placeholder="请输入"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>

                  <el-col :span="3" v-if="currentGradient.level === 1">
                    <el-form-item label="">
                      <!-- 折扣梯度新增/删除按钮 -->
                      <el-button @click="handleGradientAdd(wid, current.level)">新增</el-button>
                      <el-button
                        v-if="current.discount.length > 1"
                        @click="handleGradientDelete(wid, current.level)"
                      >
                        删除
                      </el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getCurrencyApi } from '@/api/inventory'
import { ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { cloneDeep } from 'lodash-es'

const { query } = useRoute()
const formRefs = ref<FormInstance[][][]>([])
const widList = ref<string[]>((query.wid as string).split(','))
const currencyLists = ref<Array<Array<Record<string, any>>>>([])
const markedCurrencies = ref<Array<Array<number>>>([])

// 表单数据结构
const form = ref({
  product_prices: [] as Array<{
    level: number
    currency_id?: string | number
    first_leg_logistics_fee?: string | number
    price?: string | number
    discount: Array<{
      level: number
      num?: number
      sales_price?: number
    }>
    wid: string
  }>
})

const rules = ref<FormRules>({
  currency_id: [{ required: true, message: '请选择币种', trigger: 'change' }],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: Function) => {
        if (!value || Number(value) <= 0) {
          callback(new Error('价格必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  first_leg_logistics_fee: [
    {
      validator: (rule: any, value: any, callback: Function) => {
        // 空值或大于0都通过，只有0或负数才报错
        if (value && Number(value) <= 0) {
          callback(new Error('头程物流费必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 新增折扣梯度（按仓库和币种）
const handleGradientAdd = (wid: string, level: number) => {
  const targetIndex = form.value.product_prices.findIndex(
    (item) => item.wid === wid && item.level === level
  )

  if (targetIndex === -1) return

  const currentRow = form.value.product_prices[targetIndex]

  if (currentRow.discount.length >= 5) {
    ElMessage.error('最多只能添加5个折扣梯度')
    return
  }

  // 新增折扣梯度
  currentRow.discount.push({
    level: currentRow.discount.length + 1,
    num: undefined,
    sales_price: undefined
  })
}

// 删除折扣梯度（按仓库和币种）
const handleGradientDelete = (wid: string, level: number) => {
  const targetIndex = form.value.product_prices.findIndex(
    (item) => item.wid === wid && item.level === level
  )

  if (targetIndex === -1) return

  const currentRow = form.value.product_prices[targetIndex]

  if (currentRow.discount.length <= 1) {
    ElMessage.error('至少保留一个折扣梯度')
    return
  }

  // 删除最后一个折扣梯度
  currentRow.discount.pop()
}

// 设置表单引用
const setFormRef = (warehouseIndex: number, currentIndex: number, el: FormInstance | null) => {
  if (!el) return
  if (!formRefs.value[warehouseIndex]) formRefs.value[warehouseIndex] = []
  if (!formRefs.value[warehouseIndex][currentIndex])
    formRefs.value[warehouseIndex][currentIndex] = []
  formRefs.value[warehouseIndex][currentIndex].push(el)
}

// 仓库ID列表
// const widList = ref<string[]>((query.wid as string).split(',')) // 已在上方定义

// 获取指定仓库的梯度项
const getGradientsByWid = (wid: string) => {
  return form.value.product_prices.filter((item) => item.wid === wid)
}

// 价格输入处理
const handlePriceInput = (current: any) => {
  current.price = current.price
    .replace(/[^\d.]/g, '')
    .replace(/\.{2,}/g, '.')
    .replace('.', '$#$')
    .replace(/\./g, '')
    .replace('$#$', '.')
    .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    .replace(/^\./g, '')
}

// 动态处理阶梯数量、折扣率、折扣价表单校验
const ruleFn = (
  key: string,
  currentGradientRow: Record<string, any>,
  currentGradientIndex: number
) => {
  const currentGradientRules = {
    num: () => ({
      required: true,
      trigger: ['blur', 'change'],
      validator: (_: FormRules, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入数量'))
        } else {
          if (
            currentGradientIndex &&
            parseFloat(value) <= currentGradientRow[currentGradientIndex - 1].num
          ) {
            callback(
              new Error(
                `数量${currentGradientRow[currentGradientIndex].level}数量不能小于或等于上一级数量`
              )
            )
          } else {
            callback()
          }
        }
      }
    }),
    sales_price: () => ({
      required: true,
      trigger: ['blur', 'change'],
      validator: (_: FormRules, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('请输入折扣价格'))
        } else {
          callback()
        }
      }
    })
  }
  return currentGradientRules[key]()
}

// 处理币种变更（增加仓库索引参数）
const handleChangeCurrency = (currentIndex: number, e: number) => {
  const gradient = form.value.product_prices[currentIndex]
  const warehouseIndex = widList.value.indexOf(gradient.wid)

  currencyLists.value[warehouseIndex].forEach((item: Record<string, any>) => {
    if (item.value === e) {
      item.disabled = true
      if (!markedCurrencies.value[warehouseIndex]?.includes(e)) {
        if (!markedCurrencies.value[warehouseIndex]) {
          markedCurrencies.value[warehouseIndex] = []
        }
        markedCurrencies.value[warehouseIndex].push(e)

        const checkedIds = getGradientsByWid(gradient.wid).flatMap((item: Record<string, any>) =>
          item.currency_id ? [item.currency_id] : []
        )

        currencyLists.value[warehouseIndex].forEach((item: Record<string, any>) => {
          if (
            markedCurrencies.value[warehouseIndex]
              .filter((id: number) => !checkedIds.includes(id))
              .includes(item.value)
          ) {
            item.disabled = false
          }
        })

        markedCurrencies.value[warehouseIndex] = checkedIds as number[]
      }
    }
  })
}

// 新增梯度项（受币种数量限制）
const handleItemAdd = (warehouseIndex: number) => {
  const wid = widList.value[warehouseIndex]
  const gradients = getGradientsByWid(wid)

  // 获取当前仓库可用币种
  const availableCurrencies = currencyLists.value[warehouseIndex].filter(
    (currency) => !gradients.some((g) => g.currency_id === currency.value)
  )

  if (availableCurrencies.length === 0) {
    return ElMessage.error('该仓库无可用币种可添加')
  }

  form.value.product_prices.push({
    level: gradients.length + 1,
    currency_id: availableCurrencies[0].value, // 默认选第一个可用币种
    price: '',
    first_leg_logistics_fee: '',
    discount: [{ level: 1, num: void 0, sales_price: void 0 }],
    wid
  })

  // 更新币种禁用状态
  handleChangeCurrency(form.value.product_prices.length - 1, availableCurrencies[0].value)
}

// 删除最后新增的梯度项
const handleLastItemDelete = (wid: string) => {
  const gradients = getGradientsByWid(wid)
  if (gradients.length <= 1) return

  // 获取最后一项（新增规则下最后一项即最新添加的）
  const lastGradient = gradients[gradients.length - 1]
  const warehouseIndex = widList.value.indexOf(wid)

  // 释放删除的币种
  currencyLists.value[warehouseIndex].forEach((currency) => {
    if (currency.value === lastGradient.currency_id) {
      currency.disabled = false
    }
  })

  // 从数组中删除最后一项
  const globalIndex = form.value.product_prices.findIndex(
    (item) => item.wid === wid && item.level === lastGradient.level
  )
  if (globalIndex !== -1) {
    form.value.product_prices.splice(globalIndex, 1)
  }

  // 重新计算层级
  getGradientsByWid(wid).forEach((item, index) => {
    item.level = index + 1
  })
}

// 提交梯度数据（支持多仓库）
const gradientSubmit = async () => {
  // 收集所有仓库的表单引用
  const allFormRefs = formRefs.value.flat(2).filter(Boolean)

  if (allFormRefs.length === 0) {
    return {
      product_prices: form.value.product_prices
    }
  }

  const validateResults = await Promise.all(
    allFormRefs.map(
      (formRef) =>
        new Promise((resolve) => {
          formRef?.validate((valid) => resolve(valid))
        })
    )
  )

  if (!validateResults.every((result) => result)) {
    return Promise.reject('梯度表单校验不通过')
  }

  // 验证美元和人民币相同level的num必须相等
  const usdPriceItem = form.value.product_prices.find((item) => item.currency_id === 214)
  const cnyPriceItem = form.value.product_prices.find((item) => item.currency_id === 4)

  // 只有当两个币种都存在且都有价格时才进行验证
  if (
    usdPriceItem &&
    usdPriceItem.price &&
    Number(usdPriceItem.price) > 0 &&
    cnyPriceItem &&
    cnyPriceItem.price &&
    Number(cnyPriceItem.price) > 0
  ) {
    // 获取两个币种的折扣数据
    const usdDiscounts = usdPriceItem.discount || []
    const cnyDiscounts = cnyPriceItem.discount || []

    // 创建level到num的映射
    const usdLevelNumMap = new Map()
    const cnyLevelNumMap = new Map()

    usdDiscounts.forEach((discount) => {
      if (discount.level && discount.num) {
        usdLevelNumMap.set(discount.level, Number(discount.num))
      }
    })

    cnyDiscounts.forEach((discount) => {
      if (discount.level && discount.num) {
        cnyLevelNumMap.set(discount.level, Number(discount.num))
      }
    })

    // 检查相同level的num是否相等
    for (const [level, usdNum] of usdLevelNumMap) {
      if (cnyLevelNumMap.has(level)) {
        const cnyNum = cnyLevelNumMap.get(level)
        if (usdNum !== cnyNum) {
          ElMessage.error({
            message: `美元和人民币的折扣级别${level}的数量必须相等（美元：${usdNum}，人民币：${cnyNum}）`,
            center: true
          })
          return Promise.reject('美元和人民币折扣数量验证不通过')
        }
      }
    }

    // 反向检查，确保人民币有的level美元也有相同的num
    for (const [level, cnyNum] of cnyLevelNumMap) {
      if (usdLevelNumMap.has(level)) {
        const usdNum = usdLevelNumMap.get(level)
        if (usdNum !== cnyNum) {
          ElMessage.error({
            message: `美元和人民币的折扣级别${level}的数量必须相等（美元：${usdNum}，人民币：${cnyNum}）`,
            center: true
          })
          return Promise.reject('美元和人民币折扣数量验证不通过')
        }
      }
    }
  }

  // 返回包含所有仓库的数据
  return {
    product_prices: form.value.product_prices
  }
}

// 币种查询（支持多仓库）并回显数据
const queryDropDownBox = async (
  gradientList: Array<Record<string, any>> = [],
  warehouse_parent_tree = []
) => {
  // 初始化币种列表
  currencyLists.value = []
  markedCurrencies.value = []
  initWarehouseMap(warehouse_parent_tree)
  // 为每个仓库获取币种
  for (const [index, wid] of widList.value.entries()) {
    const resp = await getCurrencyApi(wid)
    currencyLists.value[index] = resp.data.list.map((item) => ({
      ...item,
      disabled: false
    }))
    markedCurrencies.value.push([])
  }

  // 数据回显逻辑 - 如果有传入的梯度数据，则回显
  if (gradientList && gradientList.length) {
    // 1. 深拷贝传入的数据，避免响应式污染 [关键修复]
    const rawData = cloneDeep(gradientList)

    // 2. 将传入的数据按仓库分组
    const groupedData: Record<string, any[]> = {}
    rawData.forEach((item) => {
      const wid = item.wid || widList.value[0]
      if (!groupedData[wid]) {
        groupedData[wid] = []
      }
      groupedData[wid].push(item)
    })

    // 3. 处理每个仓库的数据
    const processedData: any[] = []
    Object.keys(groupedData).forEach((wid) => {
      const warehouseData = groupedData[wid]
      // 按level排序
      warehouseData.sort((a, b) => a.level - b.level)

      // 处理每个梯度项
      warehouseData.forEach((item, index) => {
        processedData.push({
          ...item,
          level: index + 1, // 确保level连续
          wid: wid
        })
      })
    })

    // 4. 设置回显数据
    form.value.product_prices = processedData

    // 5. 确保DOM更新后设置币种状态 [关键修复]
    nextTick(() => {
      form.value.product_prices.forEach((item, index) => {
        if (item.currency_id) {
          handleChangeCurrency(index, item.currency_id as number)
        }
      })
    })
  } else {
    // 没有回显数据时初始化
    form.value.product_prices = widList.value.map((wid, index) => ({
      level: 1,
      currency_id: '',
      price: '',
      first_leg_logistics_fee: '',
      discount: [
        {
          level: 1,
          num: void 0,
          sales_price: void 0
        }
      ],
      wid
    }))
  }
}
// 组件挂载后自动加载数据
onMounted(() => {
  // 实际应用中这里应该从API获取需要回显的数据
})
// 核心方法：将仓库ID转换为名称
const getWarehouseName = (wid: string) => {
  return warehouseMap.value[wid] || `未知仓库(${wid})`
}
// 仓库名称映射表（核心修复）
const warehouseMap = ref<Record<string, string>>({})

// 核心修复：初始化仓库映射表（包含虚拟仓库）
const initWarehouseMap = (warehouseData) => {
  warehouseData.forEach((virtualWarehouse) => {
    // 添加虚拟仓库映射
    warehouseMap.value[String(virtualWarehouse.value)] = virtualWarehouse.label

    // 添加物理仓库映射
    virtualWarehouse.children?.forEach((physicalWarehouse) => {
      warehouseMap.value[String(physicalWarehouse.value)] = physicalWarehouse.label
    })
  })
}
defineExpose({
  queryDropDownBox,
  gradientSubmit
})
</script>

<style lang="less" scoped>
:deep(.el-form-item) {
  width: 100%;
}

.warehouse-header {
  padding: 10px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-card {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.el-row {
  margin-bottom: 15px;

  &:last-child {
    margin-bottom: 0;
  }
}

.data-echo-hint {
  padding: 10px;
  margin: 10px 0;
  font-size: 14px;
  color: #67c23a;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
}
</style>
